package com.gitee.leijin.rbac.util;

import cn.hutool.json.JSONUtil;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.gitee.leijin.rbac.entity.User;
import org.apache.commons.lang3.time.DateUtils;

import java.util.Date;

public class JwtUtils {

    private static final String SECRET = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAr+5A/Gm2k7QRKXJDLlFcNh3KJpbN+uDZgqRXqjPMek7+n9Zy8Xr3reCANVxziBpiztLEr6tjBFNewOhoxHMs7x+L3X8OiVjXufHeOpaW9RSxAW2OcHr4PN+jz61tDxyOf8iDvrwD3ySdaIAF7az8u3ClbYsxXzUENHR4AvvhIHwWol7bMrY72xcEeAdlm33W3DMdJm+svINIhz6KkJHkSS99tGOIJ77NyhIYxGuYLwbqgU+Jkv7Obw4gXXi4WwmET7RPL8u1njwqADsuWyf3/ryrwW2up8mEyKRe+FRU8knmfldyf+x7R2gdvcXEy0OVVf3NffVgF6DB3RbaAQIIQwIDAQAB";

    public static <T> String getToken(T t) {
        // 一个月后过期
        Date expireDate = DateUtils.addMonths(new Date(), 1);

        JWTCreator.Builder builder = JWT.create()
                .withClaim(t.getClass().getSimpleName(), JSONUtil.toJsonStr(t));

        return builder.withExpiresAt(expireDate).sign(Algorithm.HMAC256(SECRET));
    }

    public static DecodedJWT verify(String token) {
        // 修改业务数据段后抛出
        //com.auth0.jwt.exceptions.SignatureVerificationException: The Token's Signature resulted invalid when verified using the Algorithm: HmacSHA256
        // 修改签名数据段后抛出
        //com.auth0.jwt.exceptions.SignatureVerificationException: The Token's Signature resulted invalid when verified using the Algorithm: HmacSHA256

        return JWT.require(Algorithm.HMAC256(SECRET)).build().verify(token);
    }

    public static <T> T parse(DecodedJWT decodedJWT, Class<T> clazz) {
        Claim claim = decodedJWT.getClaim(clazz.getSimpleName());
        if (claim == null) {
            return null;
        }
        return JSONUtil.toBean(claim.asString(), clazz);
    }

    public static void main(String[] args) {
        User user = new User();
        user.setUid(189674527);
        user.setUname("张三");

        // 生成token
        String token = getToken(user);
        System.out.println(token);

        // 校验token
        DecodedJWT verifyToken = verify("eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJVc2VyIjoie1widWlkXCI6MTg5Njc0NTI3LFwidW5hbWVcIjpcIuW8oOS4iVwifSIsImV4cCI6MTcyMjIyOTMwOH0.evju323f8F85qoqpg24PzhDna5AzdPJ8BTSQe98vBFI");

        // 解析token
        User user1 = parse(verifyToken, User.class);
        System.out.println(user1);
    }


}
